# -*- coding: utf-8 -*-
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import mapper
engine = create_engine('sqlite:///data/test.sqlite3', echo=True)

metadata = MetaData()
user_table = Table('users', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String),
    Column('fullname', String),
    Column('password', String),
)

class User(object):
    def __init__(self, name, fullname, password):
        self.name       = name
        self.fullname   = fullname
        self.password   = password
    
    def __repr__(self):
        return "<User('%s', '%s', '%s')>" % (self.name, self.fullname, self.password)

mapper(User, user_table)

class Address(Base):
    __tablename__       = 'addresses'
    
    id                  = Column(Integer, primary_key=True)
    email_address       = Column(String, nullable=False)
    user_id             = Column(Integer, ForeignKey('users.id'))
    
    user                = relationship(User, backref=backref('addresses', order_by=id))

    def __init__(self, email_address):
        self.email_address  = email.address
    
    def __repr__(self):
        return "<Address('%s')>" % self.email_address

if __name__ == '__main__':
    # metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    ed_user = User('ed', 'Ed Jones', '123')
    session.add(ed_user)
    our_user = session.query(User).filter_by(name='ed').first()
    print our_user
    session.add_all([
        User('wendy', 'Wendy Willams', 'wendy'),
        User('mary', 'Mary Contrary', 'mary'),
        User('fred', 'Fred Flinstone', 'ferd'),
    ])
    ed_user.password = 'ed123'
    print session.dirty
    print session.new
    session.commit()